﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using Cinemachine;
using GameFramework;
using GameFramework.DataTable;
using System;
using UGFExtensions.SpriteCollection;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;

namespace Adventure
{
    public class MenuForm : UGuiForm
    {

        private UIButton quitButton;

        private UIButton cancelLoginButton;
        private UIButton saveDataButton;
        private UIButton headButton;
        private UIButton AchievementButton;
        private UIButton BackpackerButton;
        private UIButton ShopButton;

        private Image headValue;

        private Text playerName;
        private Text playerLevel;
        private Text playerAttack;
        private Text playerDefense;
        private Text playerHP;
        private Text playerEXP;

        private Text goldText;
        private Text killAllText;

        private ProcedureMenu m_ProcedureMenu = null;

        private ScrollRect scrollRect;

        protected override void OnInit(object userData)
        {
            base.OnInit(userData);


            quitButton = transform.FindTransform<UIButton>("QuitButton");
            saveDataButton = transform.FindTransform<UIButton>("SaveDataButton");


            cancelLoginButton = transform.FindTransform<UIButton>("CancelLoginButton");
            AchievementButton = transform.FindTransform<UIButton>("AchievementButton");
            BackpackerButton = transform.FindTransform<UIButton>("BackpackerButton");
            ShopButton = transform.FindTransform<UIButton>("ShopButton");
            headButton = transform.FindTransform<UIButton>("HeadButton");

            headValue = transform.FindTransform<Image>("HeadValue");

            playerName = transform.FindTransform<Text>("PlayerName");
            playerLevel = transform.FindTransform<Text>("PlayerLevel");
            playerAttack = transform.FindTransform<Text>("PlayerAttack");
            playerDefense = transform.FindTransform<Text>("PlayerDefense");
            playerHP = transform.FindTransform<Text>("PlayerHP");
            playerEXP = transform.FindTransform<Text>("PlayerEXP");
            goldText = transform.FindTransform<Text>("GoldText");
            killAllText = transform.FindTransform<Text>("KillAllText");

            scrollRect = transform.FindTransform<ScrollRect>("Level Scroll View");

            for (int i = 0; i < scrollRect.GetComponentsInChildren<Text>().Length; i++)
            {
                scrollRect.GetComponentsInChildren<Text>()[i].text = GameEntry.Localization.GetString("Menu.Map", i + 1);

                var button = scrollRect.GetComponentsInChildren<UIButton>()[i];
                button.onClick.AddListener(() =>
                {
                    PlayUISound(10001);

                    GameEntry.DataNode.SetData(Constant.MenuFormMapId, (VarString)button.name);
                    GameEntry.TimerComponent.AddOnceTimer(300, () => { m_ProcedureMenu.StartGame(); });
                });
            }

            if (!GameEntry.ArchiveData.Load(Constant.Setting.UserData))
            {
                GameEntry.UI.OpenUIForm(UIFormId.LoginForm);
                GameEntry.TimerComponent.AddOnceTimer(1, () => { Close(); });
                return;
            }
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnOpen(object userData)
#else
        protected internal override void OnOpen(object userData)
#endif
        {
            base.OnOpen(userData);

            m_ProcedureMenu = (ProcedureMenu)userData;

            if (m_ProcedureMenu == null)
            {
                Log.Warning("ProcedureMenu is invalid when open MenuForm.");
                return;
            }

            UIEventTrigger.Get(saveDataButton).onClick = OnSaveDataButtonClick;

            UIEventTrigger.Get(quitButton).onClick = OnQuitButtonClick;

            UIEventTrigger.Get(cancelLoginButton).onClick = OnCancelLoginButtonClick;
            UIEventTrigger.Get(AchievementButton).onClick = OnAchievementButtonClick;
            UIEventTrigger.Get(BackpackerButton).onClick = OnBackpackerButtonClick;
            UIEventTrigger.Get(ShopButton).onClick = OnShopButtonClick;

            UIEventTrigger.Get(headButton).onClick = OnHeadButtonClick;

            Camera.main.GetComponent<CinemachineVirtualCamera>().Follow = null;
            Camera.main.GetComponent<CinemachineVirtualCamera>().LookAt = null;
            Camera.main.transform.position = new Vector3(0, 0, -10);

            scrollRect.verticalNormalizedPosition = 1;

            UpdatePlayerData();
            UpdatePlayerData();//连续刷新的情况
            UpdatePlayerData();

        }


        protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(elapseSeconds, realElapseSeconds);
            AchievementFormCheck();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnClose(bool isShutdown, object userData)
#else
        protected internal override void OnClose(bool isShutdown, object userData)
#endif
        {
            m_ProcedureMenu = null;

            base.OnClose(isShutdown, userData);

            UIEventTrigger.Get(saveDataButton).onClick = null;

            UIEventTrigger.Get(quitButton).onClick = null;


            UIEventTrigger.Get(cancelLoginButton).onClick = null;
            UIEventTrigger.Get(AchievementButton).onClick = null;
            UIEventTrigger.Get(BackpackerButton).onClick = null;
            UIEventTrigger.Get(ShopButton).onClick = null;

            UIEventTrigger.Get(headButton).onClick = null;
        }


        public void UpdatePlayerData()
        {
            PlayerData playerData = GameEntry.ArchiveData.Data.player;
            DRPlayer dRPlayer = GameEntry.DataTable.GetDRPlayer(playerData.PlayerId);
            headValue.SetSprite(Constant.SpriteCollectionPath, AssetUtility.GetUIDynamicSrpiteAsset(playerData.HeadString));

            playerName.text = GameEntry.Localization.GetString("Menu.PlayerName", playerData.User);
            if (dRPlayer==null)
            {
                return;
            }
            Log.Debug(dRPlayer);
            playerLevel.text = GameEntry.Localization.GetString("Menu.PlayerLevel", dRPlayer.Level);
            playerAttack.text = GameEntry.Localization.GetString("Menu.PlayerAttack", dRPlayer.Attack);
            playerDefense.text = GameEntry.Localization.GetString("Menu.PlayerDefense", dRPlayer.Defense);
            playerHP.text = GameEntry.Localization.GetString("Menu.PlayerHP", Utility.Text.Format("{0}/{1}", playerData.CurrentHP, dRPlayer.MaxHP));
            playerEXP.text = GameEntry.Localization.GetString("Menu.PlayerEXP", Utility.Text.Format("{0}/{1}", playerData.CurrentEXP, dRPlayer.MaxEXP));
            goldText.text = GameEntry.Localization.GetString("Menu.Gold", GameEntry.ArchiveData.Data.Gold);
            killAllText.text = GameEntry.Localization.GetString("Menu.KillAll", GameEntry.ArchiveData.Data.KillCount);
        }
        private void OnShopButtonClick(GameObject go)
        {
            Log.Info("商店系统");
            PlayUISound(10000);

            GameEntry.UI.OpenUIForm(UIFormId.ShopForm);
            Close();
        }

        private void OnBackpackerButtonClick(GameObject go)
        {
            Log.Info("背包系统");
            PlayUISound(10000);

            GameEntry.UI.OpenUIForm(UIFormId.BackpackerForm);
            Close();
        }

        public void OnAchievementButtonClick(GameObject go)
        {
            Log.Info("成就系统");
            PlayUISound(10000);

            GameEntry.UI.OpenUIForm(UIFormId.AchievementForm, this);
        }
        public void OnCancelLoginButtonClick(GameObject go)
        {
            Log.Info("取消登录");
            PlayUISound(10000);


            GameEntry.UI.OpenDialog(new DialogParams()
            {
                Mode = 2,
                Title = GameEntry.Localization.GetString("AskCancelLogin.Title"),
                Message = GameEntry.Localization.GetString("AskCancelLogin.Message"),
                OnClickConfirm = delegate (object userData)
                {
                    GameEntry.UI.OpenUIForm(UIFormId.LoginForm);
                    Close();
                },
            });
        }
        public void OnHeadButtonClick(GameObject go)
        {
            Log.Info("点击头像");
            PlayUISound(10000);
            GameEntry.UI.OpenUIForm(UIFormId.HeadForm, headValue.sprite.name);
            //Close();
        }

        private void OnSaveDataButtonClick(GameObject go)
        {
            Log.Info("保存");
            PlayUISound(10000);

            GameEntry.UI.OpenDialog(new DialogParams()
            {
                Mode = 2,
                Title = GameEntry.Localization.GetString("AskSaveData.Title"),
                Message = GameEntry.Localization.GetString("AskSaveData.Message"),
                OnClickConfirm = delegate (object userData)
                {
                    GameEntry.ArchiveData.Save();
                },
            });
        }


        public void OnQuitButtonClick(GameObject go)
        {
            Log.Info("退出游戏");
            PlayUISound(10000);

            GameEntry.UI.OpenDialog(new DialogParams()
            {
                Mode = 2,
                Title = GameEntry.Localization.GetString("AskQuitGame.Title"),
                OtherText = GameEntry.Localization.GetString("AskQuitGame.Title2"),
                Message = GameEntry.Localization.GetString("AskQuitGame.Message"),
                OnClickConfirm = delegate (object userData)
                {
                    Camera.main.GetComponent<Camera>().enabled = false;
                    UnityGameFramework.Runtime.GameEntry.Shutdown(ShutdownType.Quit);

                },
                OnClickOther = delegate (object userData) { UnityGameFramework.Runtime.GameEntry.Shutdown(ShutdownType.Restart); },
            });
        }


        public void AchievementFormCheck()
        {
            if (GameEntry.ArchiveData.Data.KillCount == 1)
            {
                AchievementForm.Finish_Task(1, false);
            }
            else
            if (GameEntry.ArchiveData.Data.KillCount == 3)
            {
                AchievementForm.Finish_Task(2, false);
            }

            if (GameEntry.ArchiveData.Data.KillCount == 5)
            {
                AchievementForm.Finish_Task(3, false);
            }

            if (GameEntry.ArchiveData.Data.KillCount == 7)
            {
                AchievementForm.Finish_Task(4, false);
            }

            if (GameEntry.ArchiveData.Data.player.PlayerId == 2)
            {
                AchievementForm.Finish_Task(5, false);
            }
            if (GameEntry.ArchiveData.Data.player.PlayerId == 3)
            {
                AchievementForm.Finish_Task(6, false);
            }

            if (GameEntry.ArchiveData.Data.ShopCount == 1)
            {
                AchievementForm.Finish_Task(7, false);
            }
            if (GameEntry.ArchiveData.Data.ShopCount == 10)
            {
                AchievementForm.Finish_Task(8, false);
            }
            if (GameEntry.ArchiveData.Data.BackpackerCount == 1)
            {
                AchievementForm.Finish_Task(9, false);
            }
            if (GameEntry.ArchiveData.Data.BackpackerCount == 10)
            {
                AchievementForm.Finish_Task(10, false);
            }

        }
    }
}
